package core

import (
	"errors"
	"fmt"
	"os/exec"
)

// 定义ptz用到的常量
const (
	LEFT       = "left"       // 向左移动
	RIGHT      = "right"      // 向右移动
	UP         = "up"         // 向上移动
	DOWN       = "down"       // 向下移动
	UP_LEFT    = "up_left"    // 向上左移动
	UP_RIGHT   = "up_right"   // 向上右移动
	DOWN_LEFT  = "down_left"  // 向下左移动
	DOWN_RIGHT = "down_right" // 向下右移动
	ZOOM_IN    = "zoom_in"    // 放大镜头
	ZOOM_OUT   = "zoom_out"   // 缩小镜头
	// 开启云台操作
	SIG_PTZ_START = "ptz_start"
	// 操作云台完成
	SIG_PTZ_END = "ptz_end"
	// 云台操成功
	SIG_PTZ_SUCCESS = "ptz_success"
	// 云台操作失败
	SIG_PTZ_FAIL = "ptz_fail"
	// 云台操作找不到
	SIG_PTZ_NOT_FOUND = "ptz_not_found"
)

type RecorderInfo struct {
	address  string // 录像机地址
	username string // 录像机用户名
	password string // 录像机密码
}

type PTZ struct {
	chNo       string // 通道号
	recordInfo RecorderInfo
}

func NewPTZ(code string) *PTZ {
	return &PTZ{
		chNo: code,
	}
}

// SetData 设置数据
func (o *PTZ) SetData(mapData map[string]any) {
	if address, ok := mapData["address"].(string); ok {
		o.recordInfo.address = address
	}
	if username, ok := mapData["username"].(string); ok {
		o.recordInfo.username = username
	}
	if password, ok := mapData["password"].(string); ok {
		o.recordInfo.password = password
	}
}

// RunDirector 运行指令
func (o *PTZ) RunDirector(director string) error {
	// 指令例子：ptz -c 51 -d zoom_out -r 10.1.6.252 -u admin -p abc2222
	args := []string{
		"-c", o.chNo,
		"-d", director,
		"-r", o.recordInfo.address,
		"-u", o.recordInfo.username,
		"-p", o.recordInfo.password,
	}
	G.Log.Infof("正在执行ptz命令:%s %s", G.App.PTZ, args)
	output, err := exec.Command(G.App.PTZ, args...).Output()
	if err != nil {
		G.Log.Errorf("执行ptz命令[%s]出错:[%s]", director, err.Error())
		return errors.New(fmt.Sprintf("[ptz]执行命令[%s]出错", director))
	}
	G.Log.Infof("执行ptz命令[%s]结果：[%s]", director, string(output))
	return nil
}
